package pro.bbs.view.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.yy.constant.AppConstant;
import com.yy.kit.log.YYLogKits;
import com.yy.kit.object.YYObjectKits;
import com.yy.kit.string.YYStrKits;
import com.yy.pojo.base.TUser;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import pro.bbs.view.annotation.IsLogin;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;

/**
 * <p>
 * session拦截器，判断用户是否登陆
 * </p>
 *
 * @author 杨阳
 * @since 2017年9月1日14:54:54
 */
public class SessionInterceptor implements HandlerInterceptor {

    @Override
    public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3) throws Exception {

    }

    @Override
    public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3) throws Exception {

    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        YYLogKits.info(SessionInterceptor.class, "┌───────────────────────────────────────────────────────────────────────────┐");
        String uri = request.getRequestURI();
        //是否是ajax请求的标识，因为跳转页面与ajax处理方式需要分别处理。
        //1.ajax直接使用response write 返回给用户
        //2.跳转页面直接跳转到登陆页
        boolean isAjaxRequest = false;
        if (!YYStrKits.isBlank(request.getHeader("x-requested-with")) && "XMLHttpRequest".equals(request.getHeader("x-requested-with"))) {
            //这个就是ajax请求
            isAjaxRequest = true;
        }

        // 获得Controller类或者方法上的注解 @IsLogin
        if (handler instanceof HandlerMethod) {
            IsLogin login = ((HandlerMethod) handler).getMethodAnnotation(IsLogin.class);
            if (YYObjectKits.isNull(login)) {//没有得到注解，直接放过，不做拦截
                YYLogKits.info(SessionInterceptor.class, "├用户会话拦截器，用户请求URI:{} ，没有发现@IsLogin，放过检查...", request.getRequestURI());
                YYLogKits.info(SessionInterceptor.class, "└───────────────────────────────────────────────────────────────────────────┘");
                return true;
            }

            HttpSession session = request.getSession();
            TUser user = (TUser) session.getAttribute(AppConstant.SESSION_KEY);
            if (YYObjectKits.isNull(user)) {
                if (isAjaxRequest) {//ajax请求，使用response返回结果
                    JSONObject json = new JSONObject();
                    json.put("success", Boolean.FALSE);
                    json.put("msg", "session已经失败，请重新登陆!");
                    PrintWriter writer = response.getWriter();
                    writer.write(json.toString());
                    writer.close();
                    response.flushBuffer();
                    return false;
                } else {
                    //不是ajax请求，跳转到登陆页面
                    YYLogKits.info(SessionInterceptor.class, "├session失效，跳转到登陆页面....");
                    YYLogKits.info(SessionInterceptor.class, "└───────────────────────────────────────────────────────────────────────────┘");
                    response.sendRedirect("/");
                    return false;
                }
            } else {
                YYLogKits.info(SessionInterceptor.class, "├用户正常登陆，放过检查....");
                YYLogKits.info(SessionInterceptor.class, "└───────────────────────────────────────────────────────────────────────────┘");
                return true;
            }
        }
        return true;
    }

}
